<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller
{
    protected $_templates;
	
    public function __construct()
	{
        parent::__construct();
        $this->load->model('login_model','login');
    }

    public function index()
	{  
       
        if($this->session->userdata('admin_id')){
            redirect('admincp');
        } 
		if(isset($_POST['bt_submit']))
		{
			$security_code = $this->session->userdata('security_code') ;
			$captcha = $this->input->post('captcha');
			$user_name = $this->input->post('user_login');
			$password = md5($this->input->post('user_pass'));
			
			//trit($captcha .'=='. $security_code);
			if(!empty($captcha) && ($captcha == $security_code))
			{
				$this->form_validation->set_rules('user_login',lang('login_name'),'trim|required|callback_check_login');
				$this->form_validation->set_rules('user_pass',lang('login_password'),'trim|required');
				if($this->form_validation->run())
				{
					if($this->login->get_admin($user_name,$password))
					{
						$this->session->set_flashdata('message',"Đăng nhập thành công");
						redirect(base_url().'admincp');
					}else{
						$this->session->set_flashdata('message',"Đăng nhập không thành công");
					}
				}
			}
			else
			{
				$this->session->set_userdata('message',"Mã lệnh không hợp lệ"); 
			}
		}
        $this->load->view('login/index');
    }

    function check_login($user_login)
	{
        $password= md5($this->input->post('user_pass'));
        if(($user_login!='') && ($password!=''))
		{
            if($this->login->check_login($user_login,$password))
			{
                return true;
            }
			else
			{
                $this->form_validation->set_message('check_login',lang('login_fail_info'));
                return false;
            }
        }
		else
		{
            $this->form_validation->set_message('check_login',lang('login_name_pass_not_empty'));
            return false;
        }
    }

	public function captcha()
	{
		$md5_hash = md5(rand(0,999)); 
		$security_code = substr($md5_hash, 15, 5); 
		//$_SESSION["security_code"] = $security_code;
		$this->session->set_userdata(array('security_code'=>$security_code)) ;
		$width = 100; 
		$height = 28;  
		$image = imagecreate($width, $height);  
		$white = imagecolorallocate($image, 255, 255, 255); 
		$black = imagecolorallocate($image, 0, 0, 0); 
		imagefill($image, 0, 0, $black); 
		imagestring($image, 10, 28, 6, $security_code, $white); 
		header("Content-Type: image/jpeg"); 
		imagejpeg($image); 
		imagedestroy($image); 
	}
	
    function logout()
	{
		$this->session->sess_destroy();
		redirect(base_url());          
    }       
}
?>